package com.rio.helper;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.rio.core.L;
import com.rio.core.U;

import android.content.ContentValues;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

public class NetworkHelper {

	private static ConnectivityManager mConnectManager;

	private static final int TIMEOUT = 1;
	private static final int TIMES = 1;

	public static Uri uri = Uri.parse("content://telephony/carriers");

	/**
	 * 检查网络是否通畅<br>
	 * 需要权限 android.permission.ACCESS_NETWORK_STATE
	 * 
	 * @param mContext
	 * @return
	 */
	public static boolean isAvailable(Context mContext) {
		if (mConnectManager == null)
			mConnectManager = (ConnectivityManager) mContext
					.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo[] info = mConnectManager.getAllNetworkInfo();
		if (info != null) {
			int l = info.length;
			for (int i = 0; i < l; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			L.e(ex);
		}
		return null;
	}


	public static String TYPE_NONE = "NONE";
	public static String TYPE_WIFI = "WIFI";
	public static String TYPE_3G = "3G";
	public static String TYPE_2G = "2G";
	
	
	/**
	 * 检查当前网络是2G还是3G,或者wifi
	 */
	public static String getNetWorkType(Context mContext) {

		String netCode = TYPE_NONE;

		if (isAvailable(mContext)) {
			WifiManager mWifiManager = (WifiManager) mContext
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
			int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();

			if (mWifiManager.isWifiEnabled() && ipAddress != 0) {

				netCode = TYPE_WIFI;

			} else {

				TelephonyManager telMgr = (TelephonyManager) mContext
						.getSystemService(Context.TELEPHONY_SERVICE);

				int networkType = 0;
				if (telMgr != null) {
					networkType = telMgr.getNetworkType();

					switch (networkType) {

					// 3G
					case TelephonyManager.NETWORK_TYPE_HSDPA:
					case TelephonyManager.NETWORK_TYPE_HSPA:
					case TelephonyManager.NETWORK_TYPE_UMTS:
					case TelephonyManager.NETWORK_TYPE_EVDO_0:
					case TelephonyManager.NETWORK_TYPE_EVDO_A: {
						netCode = TYPE_3G;
					}
						break;

					// 2G
					case TelephonyManager.NETWORK_TYPE_GPRS:
					case TelephonyManager.NETWORK_TYPE_EDGE:
					case TelephonyManager.NETWORK_TYPE_CDMA: {
						netCode = TYPE_2G;
					}
						break;

					default:
						break;
					}
				}

			}
		}
		return netCode;
	}

	public static boolean checkNetState(Context context) {
		boolean netstate = false;
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						netstate = true;
						break;
					}
				}
			}
		}
		return netstate;
	}

	/**
	 * 判断网络是否为漫游
	 */
	public static boolean isNetworkRoaming(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			L.i("couldn't get connectivity manager");
		} else {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null
					&& info.getType() == ConnectivityManager.TYPE_MOBILE) {
				TelephonyManager tm = (TelephonyManager) context
						.getSystemService(Context.TELEPHONY_SERVICE);
				if (tm != null && tm.isNetworkRoaming()) {
					L.i("network is roaming");
					return true;
				} else {
					L.i("network is not roaming");
				}
			} else {
				L.i("not using mobile network");
			}
		}
		return false;
	}

	/**
	 * 判断MOBILE网络是否可用
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static boolean isMobileDataEnable(Context context) throws Exception {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean isMobileDataEnable = false;

		isMobileDataEnable = connectivityManager.getNetworkInfo(
				ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();

		return isMobileDataEnable;
	}

	/**
	 * 判断wifi 是否可用
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static boolean isWifiDataEnable(Context context) throws Exception {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean isWifiDataEnable = false;
		isWifiDataEnable = connectivityManager.getNetworkInfo(
				ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
		return isWifiDataEnable;
	}



	/**
	 * 是否设置wap代理
	 * 
	 * @return
	 */
	public static boolean isWap() {
		String proxyHost = android.net.Proxy.getDefaultHost();
		if (proxyHost != null) {
			return true;
		} else {
			return false;
		}
	}

	public static String getDefaultHost() {
		String proxyHost = Proxy.getDefaultHost();
		return TextUtils.isEmpty(proxyHost) ? null : proxyHost;
	}

	public static byte[] ipstr2ipbyte(String ipstr) {
		byte[] ip = new byte[4];
		int i = 0;
		for (String str : ipstr.split("[.]")) {
			ip[i++] = (byte) Integer.parseInt(str);
		}
		return ip;
	}

	public static String ipbyte2ipstr(byte[] ip) {
		String ipStr = "";
		for (int i = 0; i < ip.length; i++) {
			ipStr += Integer.toString(byte2int(ip[i]));
			if (i < (ip.length - 1)) {
				ipStr += ".";
			}
		}
		return ipStr;
	}

	public static int byte2int(byte b) {
		if (b >= 0) {
			return b;
		} else {
			return b + 256;
		}
	}

	public static byte[] int2byte(int i) {
		byte[] bt = new byte[4];
		bt[0] = (byte) (0xff & i);
		bt[1] = (byte) ((0xff00 & i) >> 8);
		bt[2] = (byte) ((0xff0000 & i) >> 16);
		bt[3] = (byte) ((0xff000000 & i) >> 24);
		return bt;
	}

	public static int byte2int(byte[] bytes) {
		int num = bytes[0] & 0xFF;
		num |= ((bytes[1] << 8) & 0xFF00);
		num |= ((bytes[2] << 16) & 0xFF0000);
		num |= ((bytes[3] << 24) & 0xFF000000);
		return num;
	}

	public static String int2ipstr(int i) {
		return ipbyte2ipstr(int2byte(i));
	}

	public static boolean pingSocket(String host) throws IOException {
		InetAddress ia = InetAddress.getByName(host);
		return ia.isReachable(1000 * TIMEOUT);
	}

	public static boolean pingSocket(String host, int port) {
		boolean isPassed = true;
		InetSocketAddress address = new InetSocketAddress(host, port);
		Socket client = new Socket();
		try {
			client.connect(address, 1000 * TIMEOUT);
		} catch (Exception e) {
			isPassed = false;
		}
		return isPassed;
	}

}
